//
//  PopularVC.swift
//  movieInfo
//
//  Created by zhangkai on 2023/7/2.
//

import UIKit

class PopularVC: UIViewController, PNChartDelegate,UITableViewDelegate,UITableViewDataSource{
    
    var bar_Chart:PNBarChart!
    var tableView:UITableView!
    var arr:[Movie] = []
    var fenleiarr:[Movie] = []
    
    var allArr:[[Movie]] = []
    
    var stattLabel:UILabel!
    var index = 0

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        
        self.allArr = [[],[],[],[],[],[],[]]
        
        let barChart = PNBarChart(frame:CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width - 20, height: 240))
        self.bar_Chart = barChart
        barChart.showLabel = true
//        barChart.showLevelLine = true
        barChart.showChartBorder = true
        barChart.isShowNumbers = true
        barChart.isGradientShow = true
        barChart.barRadius = 5;
        barChart.labelTextColor = .black
        // barChart.xLabelWidth = 10.f;
//        barChart.yChartLabelWidth = 10;
//        barChart.chartMarginLeft = 15;
//        barChart.chartMarginRight = 15;
        barChart.chartMarginTop = 5;
        barChart.chartMarginBottom = 10;
        barChart.labelMarginTop = 5.0;//X坐标刻度的上边距
        
        
        
         
        

        
        barChart.strokeColors = [UIColor.red,UIColor.blue,UIColor.blue,UIColor.blue,UIColor.blue,UIColor.blue,UIColor.blue]
        barChart.xLabels = ["Adventure","Thriller", "Animation","Actions", "comedy","Fantasy","War"];
        barChart.yValues = ["0", "0","0", "0","0","0","0"];
//        barChart.yLabelFormatter = { [weak self] yLabelValue in
//            return "\(yLabelValue)"
//        }
        barChart.stroke()
        self.view.addSubview(barChart)
        barChart.snp.makeConstraints { make in
            make.top.equalTo(topLayoutGuide.snp.bottom).offset(10)
            make.left.equalToSuperview().offset(10);
            make.height.equalTo(240)
            make.width.equalTo(UIScreen.main.bounds.width - 20)
        }
        barChart.delegate = self

        
        stattLabel = UILabel()
        stattLabel.text = "Take risks"
        stattLabel.textColor = .black
        stattLabel.font = UIFont.boldSystemFont(ofSize: 18)
        view.addSubview(stattLabel)
        stattLabel.snp.makeConstraints { make in
            make.top.equalTo(barChart.snp.bottom).offset(0)
            make.left.equalToSuperview().offset(10);
            make.height.equalTo(40)
        }
//        stattLabel.backgroundColor = .yellow
        
        
        
        tableView = UITableView(frame: CGRectZero, style: .plain)
        tableView.register(searchViewVCCell.self, forCellReuseIdentifier: "searchViewVCCell")

        tableView.backgroundColor = .secondarySystemBackground
        tableView.rowHeight = 190
//        tableView.estimatedSectionFooterHeight = 0.01
//        tableView.estimatedSectionHeaderHeight = 0.01
//        tableView.tableFooterView = UIView()
        tableView.separatorStyle = .none
//        tableView.showsVerticalScrollIndicator = false
        tableView.delegate = self
        tableView.dataSource = self
//        tableView.isHidden = true
        view.addSubview(tableView)
        tableView.snp.makeConstraints { make in
            make.top.equalTo(stattLabel.snp.bottom).offset(0)
            make.left.equalToSuperview()
            make.right.equalToSuperview()
            make.bottom.equalToSuperview()
        }
        
        
        self.index = 0
        for i in 1..<4{
            
            getInfo(page: i)
            
        }
        

    }
    
    func relaodUI(){
        
        var arr0:[Movie] = []
        for (_,temp) in self.fenleiarr.enumerated(){
            let arr3 = temp.genreIds ?? []
            
            if arr3.contains(12){
                arr0.append(temp)
            }
        }
        var arr1:[Movie] = []
        for (_,temp) in self.fenleiarr.enumerated(){
            let arr3 = temp.genreIds ?? []
            
            if arr3.contains(16){
                arr1.append(temp)
            }
        }
        var arr2:[Movie] = []
        for (_,temp) in self.fenleiarr.enumerated(){
            let arr3 = temp.genreIds ?? []
            
            if arr3.contains(53){
                arr2.append(temp)
            }
        }
        var arr33:[Movie] = []
        for (_,temp) in self.fenleiarr.enumerated(){
            let arr3 = temp.genreIds ?? []
            
            if arr3.contains(28){
                arr33.append(temp)
            }
        }
        var arr4:[Movie] = []
        for (_,temp) in self.fenleiarr.enumerated(){
            let arr3 = temp.genreIds ?? []
            
            if arr3.contains(35){
                arr4.append(temp)
            }
        }
        var arr5:[Movie] = []
        for (_,temp) in self.fenleiarr.enumerated(){
            let arr3 = temp.genreIds ?? []
            
            if arr3.contains(14){
                arr5.append(temp)
            }
        }
        var arr6:[Movie] = []
        for (_,temp) in self.fenleiarr.enumerated(){
            let arr3 = temp.genreIds ?? []
            
            if arr3.contains(10752){
                arr6.append(temp)
            }
        }
        
        self.allArr = []
        self.allArr.append(arr0)
        self.allArr.append(arr1)
        self.allArr.append(arr2)
        self.allArr.append(arr33)
        self.allArr.append(arr4)
        self.allArr.append(arr5)
        self.allArr.append(arr6)

        self.bar_Chart.yValues = ["\(arr0.count)","\(arr1.count)","\(arr2.count)","\(arr33.count)","\(arr4.count)","\(arr5.count)","\(arr6.count)"]
        
        self.bar_Chart.strokeColors = [UIColor.red,UIColor.blue,UIColor.blue,UIColor.blue,UIColor.blue,UIColor.blue,UIColor.blue]
        
        let arr00 = self.bar_Chart.xLabels as? [String] ?? []
        if arr00.count > 0{
            self.stattLabel.text = arr00[0]
        }
        
        self.arr = self.allArr.first ?? []
        self.tableView.reloadData()
        self.bar_Chart.stroke()
        
        
        
        
    }
    
    
    func getInfo(page:Int){
        
        let twourl = MMNetWork.shared.getNewWeekInfoURL(page: 2)
        
        MMNetWork.shared.fetchData(urlString: twourl, castType: [Movie].self, keyPath: "results") { result in
            switch result {
            case .success(let movies):
//                completed(.success(movies))
                
                DispatchQueue.main.async {
                    self.fenleiarr.append(contentsOf: movies)
//                    self.fenleiarr.append(contentsOf: movies)
                    self.index = self.index + 1
                    if self.index == 3{
                        self.relaodUI()
                    }
                }
                
                
                break
            case .failure(let _):

                self.index = self.index + 1
                
                DispatchQueue.main.async {
                    if self.index == 3{
                        self.relaodUI()
                    }
                }
                
                break
            }
        }
        
        
    }
    
    func userClickedOnBar(at barIndex: Int) {
        
        let bar = self.bar_Chart.bars[barIndex] as? PNBar ?? PNBar()
//        PNBar *bar = self.barChart.bars[(NSUInteger) barIndex];

        let animation = CABasicAnimation(keyPath: "transform.scale")
        animation.fromValue = 1.0
        animation.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeInEaseOut)
        animation.toValue = 1.1
        animation.duration = 0.2;
        animation.repeatCount = 0;
        animation.autoreverses = true;
        animation.isRemovedOnCompletion = true;
        animation.fillMode = CAMediaTimingFillMode.forwards;
        bar.layer.add(animation, forKey: "Float")

        DispatchQueue.main.asyncAfter(deadline: .now()+0.5){
            
            DispatchQueue.main.async {
                
                let arr = self.bar_Chart.xLabels as? [String] ?? []
                if arr.count > barIndex{
                    self.stattLabel.text = arr[barIndex]
                    self.arr = self.allArr[barIndex]
                    self.tableView.reloadData()
                }
                
                let colArr = self.bar_Chart.strokeColors as? [UIColor] ?? []
                var colArrs:[UIColor] = []
                for (i,_) in colArr.enumerated(){
                    if i == barIndex{
                        colArrs.append(UIColor.red)
                    }else{
                        colArrs.append(UIColor.blue)
                    }
                }
                self.bar_Chart.strokeColors = colArrs
                self.bar_Chart.stroke()
            }
            
            
        }
        
        
    }
    
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destination.
        // Pass the selected object to the new view controller.
    }
    */
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

        return arr.count
        
       
   }
   
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell:searchViewVCCell = tableView.dequeueReusableCell(withIdentifier: "searchViewVCCell") as? searchViewVCCell ?? searchViewVCCell()
        cell.selectionStyle = .none

        if let path = self.arr[indexPath.row].posterPath {
            cell.img.downloadImage(fromPath: path)
        }
        cell.nameLabel.text = self.arr[indexPath.row].title ?? ""
        cell.stattLabel.text = "\(self.arr[indexPath.row].voteAverage ?? 0.0)"
        cell.infoLabel.text = self.arr[indexPath.row].overview ?? ""
        
        return cell
    }
    
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        let movieInfo = self.arr[indexPath.row]
        let destVC = ViewControllerInfoVC()
        destVC.model = movieInfo
        self.navigationController?.pushViewController(destVC, animated: true)
        
        
    }

}
